from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_core.output_parsers import StrOutputParser

import asyncio
import json
import os
os.environ["OPENAI_API_BASE"] = "http://192.168.2.45:8000/v1"
os.environ["OPENAI_API_KEY"] = "xxx"

llm = ChatOpenAI(temperature=0,max_tokens=2000)

system_prompt = """ 我希望你能够帮我生成一个用户画像,依据我提供的一些信息,例如用户最近的聊天记录,和最近的话题浏览记录.
我需要用生成的用户画像来预测用户对某些话题的兴趣程度.
"""

human_prompt = """
聊天记录:{message}

话题浏览记录:{topic}
"""

async def get_user_prompt(dic:dict):
    prompt = ChatPromptTemplate.from_messages([
        SystemMessagePromptTemplate.from_template(system_prompt),
        HumanMessagePromptTemplate.from_template(human_prompt)
    ])

    if "articles" not in dic or "talks" not in dic:
        return 0

    article = ""
    for item in dic["articles"]:
        article += item["article_name"] + "\n"

    message = ""
    for item in dic["talks"]:
        if "type" in item and item["type"] == "1":
            message += item["content"] + "\n"


    chain=prompt | llm | StrOutputParser()
    res=''
    for item in chain.stream({"message": message,"topic": article}):
        res += item
    print(res)


if __name__ == "__main__":
    pass
    # 打开文件
    with open('/home/xiaoji-ai/下载/媒体/文章聊天数据.json', 'r') as f:
        # 读取文件内容
        data = f.read()
    # 解析JSON数据
    parsed_data = json.loads(data)
    ASYNCIO_LOOP = asyncio.get_event_loop()
    ASYNCIO_LOOP.run_until_complete(get_user_prompt(parsed_data))

    # if isinstance(parsed_data["res"][0], dict):
    #     print(parsed_data["res"][0].keys())
    asyncio.run(get_user_prompt(parsed_data["res"][0]))

